<template>
  <div class="container">
    <Breadcrumb :items="['分账管理', '分账模板']">
      <template #icon>
        <icon-copy />  <!-- 文档复制图标，表示模板的概念 -->
      </template>
    </Breadcrumb>
    
    <!-- 搜索区域 -->
    <a-card class="general-card" :bordered="false">
      <a-row class="search-area">
        <a-col flex="auto">
          <a-form :model="searchForm" layout="inline">
            <a-form-item field="templateName" label="模板名称">
              <a-input v-model="searchForm.templateName" placeholder="请输入模板名称" allow-clear />
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="search">
                  <template #icon><icon-search /></template>
                  查询
                </a-button>
                <a-button @click="reset">
                  <template #icon><icon-refresh /></template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col flex="86px" style="text-align: right">
          <a-button type="primary" @click="openCreateDialog">
            <template #icon><icon-plus /></template>
            新增
          </a-button>
        </a-col>
      </a-row>
      
      <!-- 表格 -->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        class="mt-4"
      >
        <template #templateType="{ record }">
          {{ record.templateType === 1 ? '按比例分成' : '按固定服务费分成' }}
        </template>
        <template #status="{ record }">
          <a-switch
            :model-value="record.status === 1"
            @change="(value) => handleStatusChange(record, value)"
          />
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="openEditDialog(record)">
              编辑
            </a-button>
            <a-button type="text" size="small" @click="openRelationDialog(record)">
              关联
            </a-button>
            <a-popconfirm
              content="确定要删除这条记录吗？"
              @ok="handleDelete(record)"
            >
              <a-button type="text" size="small" status="danger">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑对话框 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      @ok="handleSubmit"
      @cancel="closeDialog"
      :width="800"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col-props="{ span: 4 }"
        :wrapper-col-props="{ span: 19 }"
        @submit="handleSubmit"
      >
        <a-form-item field="templateName" label="模板名称" required>
          <a-input v-model="formData.templateName" placeholder="请输入模板名称" />
        </a-form-item>
        <a-form-item field="templateCode" label="模板编码" required>
          <a-input v-model="formData.templateCode" placeholder="请输入模板编码" />
        </a-form-item>
        <a-form-item field="templateType" label="模板类型" required>
          <a-radio-group v-model="formData.templateType">
            <a-radio :value="1">按比例分成</a-radio>
            <a-radio :value="2">按服务费分成</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-switch v-model="formData.status" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="formData.remark" placeholder="请输入备注" />
        </a-form-item>

        <!-- 分账明细 -->
        <a-divider>分账明细</a-divider>
        <div v-for="(item, index) in formData.items" :key="index" class="item-form">
          <template v-if="item.receiverType === 'PERSONAL_OPENID'">
            <a-row class="mb-4">
              <a-col :span="12">
                <a-form-item
                  label="手机号查询"
                  :label-col-props="{ span: 8 }"
                  :wrapper-col-props="{ span: 16 }"
                >
                  <a-input-group>
                    <a-input
                      v-model="item.mobile"
                      placeholder="请输入手机号"
                      allow-clear
                      style="width: calc(100% - 80px)"
                    />
                    <a-button
                      type="primary"
                      @click="() => handleMobileSearch(index, item.mobile)"
                      :disabled="!item.mobile"
                    >
                      查询
                    </a-button>
                  </a-input-group>
                </a-form-item>
              </a-col>
            </a-row>
          </template>
          <a-row>
            <a-col :span="12">
              <a-form-item
                :field="'items.' + index + '.receiverType'"
                label="接收方类型"
                :label-col-props="{ span: 8 }"
                :wrapper-col-props="{ span: 16 }"
                required
              >
                <a-select 
                  v-model="item.receiverType"
                  @change="() => handleReceiverTypeChange(index)"
                >
                  <a-option value="MERCHANT_ID">商户号</a-option>
                  <a-option value="PERSONAL_OPENID">个人openid</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :field="'items.' + index + '.receiverAccount'"
                label="接收方账号"
                :label-col-props="{ span: 8 }"
                :wrapper-col-props="{ span: 16 }"
                required
              >
                <a-input 
                  v-model="item.receiverAccount" 
                  :placeholder="item.receiverType === 'PERSONAL_OPENID' ? 'openid将自动填充' : '请输入接收方账号'"
                  :disabled="item.receiverType === 'PERSONAL_OPENID'"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2" class="delete-btn">
              <a-button
                v-if="index > 0"
                type="text"
                status="danger"
                @click="removeItem(index)"
              >
                <icon-delete />
              </a-button>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item
                :field="'items.' + index + '.receiverName'"
                label="接收方名称"
                :label-col-props="{ span: 8 }"
                :wrapper-col-props="{ span: 16 }"
                required
              >
                <a-input v-model="item.receiverName" placeholder="请输入接收方名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <template v-if="formData.templateType === 1">
                <a-form-item
                  :field="'items.' + index + '.ratio'"
                  label="分成比例"
                  :label-col-props="{ span: 8 }"
                  :wrapper-col-props="{ span: 16 }"
                  required
                >
                  <a-input-number
                    v-model="item.ratio"
                    :min="0"
                    :max="100"
                    :precision="2"
                    placeholder="请输入分成比例"
                  >
                    <template #append>%</template>
                  </a-input-number>
                </a-form-item>
              </template>
              <template v-else>
                <a-form-item
                  :field="'items.' + index + '.fixedAmount'"
                  label="固定服务费"
                  :label-col-props="{ span: 8 }"
                  :wrapper-col-props="{ span: 16 }"
                  required
                >
                  <a-input-number
                    v-model="item.fixedAmount"
                    :min="0"
                    :precision="3"
                    placeholder="请输入固定服务费"
                  >
                    <template #append>元/度</template>
                  </a-input-number>
                </a-form-item>
              </template>
            </a-col>
          </a-row>
        </div>
        <div class="add-item">
          <a-button type="dashed" long @click="addItem">
            <template #icon><icon-plus /></template>
            添加分账明细
          </a-button>
        </div>
      </a-form>
    </a-modal>

    <!-- 关联对话框 -->
    <a-modal
      v-model:visible="relationDialogVisible"
      title="模板关联"
      :ok-button="false"
      :cancel-button="false"
      @cancel="closeRelationDialog"
      :width="600"
    >
      <div class="relation-header">
        <div class="title">关联列表</div>
        <a-button type="primary" size="small" @click="handleAddRelation">
          <template #icon><icon-plus /></template>
          新增关联
        </a-button>
      </div>

      <!-- 关联表单 -->
      <a-form
        v-if="showRelationForm"
        ref="relationFormRef"
        :model="relationFormData"
        :rules="relationRules"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="partnerId" label="合伙人">
          <a-select
            v-model="relationFormData.partnerId"
            placeholder="请选择合伙人"
            allow-clear
            @change="handlePartnerChange"
          >
            <a-option
              v-for="item in partnerOptions"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </a-select>
        </a-form-item>
        <a-form-item field="chargingGroupId" label="站点">
          <a-select
            v-model="relationFormData.chargingGroupId"
            placeholder="请选择站点"
            allow-clear
            :disabled="!relationFormData.partnerId"
          >
            <a-option
              v-for="item in chargingGroupOptions"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-switch v-model="relationFormData.status" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
        <div class="form-actions">
          <a-space>
            <a-button @click="cancelRelationForm">取消</a-button>
            <a-button type="primary" @click="submitRelationForm">确定</a-button>
          </a-space>
        </div>
      </a-form>

      <!-- 关联列表 -->
      <a-table
        :loading="relationLoading"
        :data="relationData"
        :pagination="false"
        :bordered="false"
        size="small"
        class="mt-4"
      >
        <template #columns>
          <a-table-column title="站点" data-index="chargingGroupName">
            <template #cell="{ record }">
              {{ record.chargingGroupId === 0 ? '全部站点' : record.chargingGroupName }}
            </template>
          </a-table-column>
          <a-table-column title="合伙人" data-index="partnerId">
            <template #cell="{ record }">
              {{ partnerOptions.find(item => item.id === record.partnerId)?.name }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleRelationEdit(record)">
                  编辑
                </a-button>
                <a-popconfirm
                  content="确定要删除这条关联吗？"
                  @ok="handleRelationDelete(record)"
                >
                  <a-button type="text" size="small" status="danger">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import {
  getProfitSharingTemplateList,
  getProfitSharingTemplateDetail,
  createProfitSharingTemplate,
  updateProfitSharingTemplate,
  deleteProfitSharingTemplate
} from '@/api/profit';
import { IconCopy } from '@arco-design/web-vue/es/icon';
import {
  createRelation,
  updateRelation,
  deleteRelation,
  getRelationsByTemplateId
} from '@/api/profitRelation';
import type { ProfitSharingTemplateRelation } from '@/types/profit';
import { getAllPartners } from '@/api/partner';
import { getAllCarChargingGroups } from '@/api/car-charging-group';
import type { Result } from '@/types/global';
import { getUserByMobile } from '@/api/member';
import type { Member } from '@/api/member';

const formRef = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('创建分账模板');
const isEdit = ref(false);

// 搜索表单
const searchForm = reactive({
  templateName: '',
});

// 表格列定义
const columns: TableColumnData[] = [
  {
    title: '模板名称',
    dataIndex: 'templateName',
  },
  {
    title: '模板编码',
    dataIndex: 'templateCode',
  },
  {
    title: '模板类型',
    dataIndex: 'templateType',
    slotName: 'templateType',
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
  },
];

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 表格数据
const renderData = ref([]);

// 表单数据
const formData = reactive({
  id: '' as string | number,
  templateName: '',
  templateCode: '',
  templateType: 1,
  rateType: 0,
  status: 1,
  remark: '',
  items: [
    {
      receiverType: 'MERCHANT_ID',
      receiverAccount: '',
      receiverName: '',
      ratio: undefined as number | undefined,
      fixedAmount: undefined as number | undefined,
      mobile: ''
    }
  ],
});

// 表单校验规则
const rules = {
  templateName: [{ required: true, message: '请输入模板名称' }],
  templateCode: [{ required: true, message: '请输入模板编码' }],
  templateType: [{ required: true, message: '请选择模板类型' }],
  'items.*.receiverType': [{ required: true, message: '请选择接收方类型' }],
  'items.*.receiverAccount': [{ required: true, message: '请输入接收方账号' }],
  'items.*.receiverName': [{ required: true, message: '请输入接收方名称' }],
  'items.*.ratio': [{ 
    required: true, 
    message: '请输入分成比例',
    type: 'number',
    validator: (value: number, cb: (error?: string) => void) => {
      if (formData.templateType === 1 && !value && value !== 0) {
        cb('请输入分成比例');
      } else {
        cb();
      }
    }
  }],
  'items.*.fixedAmount': [{ 
    required: true, 
    message: '请输入固定服务费',
    type: 'number',
    validator: (value: number, cb: (error?: string) => void) => {
      if (formData.templateType === 2 && !value && value !== 0) {
        cb('请输入固定服务费');
      } else {
        cb();
      }
    }
  }],
};

// 获取列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const { data } = await getProfitSharingTemplateList({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      templateName: searchForm.templateName,
    });
    renderData.value = data.records;
    pagination.total = data.total;
  } catch (error) {
    console.error('获取分账模板列表失败:', error);
    Message.error('获取分账模板列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const search = () => {
  pagination.current = 1;
  fetchData();
};

// 重置
const reset = () => {
  searchForm.templateName = '';
  search();
};

// 分页变化
const onPageChange = (current: number) => {
  pagination.current = current;
  fetchData();
};

// 打开创建对话框
const openCreateDialog = () => {
  isEdit.value = false;
  dialogTitle.value = '创建分账模板';
  dialogVisible.value = true;
  Object.assign(formData, {
    id: undefined,
    templateName: '',
    templateCode: '',
    templateType: 1,
    rateType: 0,
    status: 1,
    remark: '',
    items: [
      {
        receiverType: 'MERCHANT_ID',
        receiverAccount: '',
        receiverName: '',
        ratio: undefined,
        fixedAmount: undefined,
        mobile: ''
      }
    ],
  });
};

// 打开编辑对话框
const openEditDialog = async (record: any) => {
  isEdit.value = true;
  dialogTitle.value = '编辑分账模板';
  dialogVisible.value = true;
  try {
    const { data } = await getProfitSharingTemplateDetail(record.id);
    Object.assign(formData, data);
  } catch (error) {
    console.error('获取分账模板详情失败:', error);
    Message.error('获取分账模板详情失败');
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
};

// 添加分账明细
const addItem = () => {
  formData.items.push({
    receiverType: 'MERCHANT_ID',
    receiverAccount: '',
    receiverName: '',
    ratio: undefined,
    fixedAmount: undefined,
    mobile: ''
  });
};

// 删除分账明细
const removeItem = (index: number) => {
  formData.items.splice(index, 1);
};

// 提交表单
const handleSubmit = async () => {
  try {
    console.log('开始验证表单');
    const errors = await formRef.value?.validate().catch((errors: any) => errors);
    console.log('表单验证结果:', errors);
    if (errors) {
      console.log('表单验证失败:', errors);
      return;
    }

    console.log('提交的表单数据:', formData);
    if (isEdit.value) {
      await updateProfitSharingTemplate(formData.id, formData);
      Message.success('更新成功');
    } else {
      await createProfitSharingTemplate(formData);
      Message.success('创建成功');
    }
    closeDialog();
    fetchData();
  } catch (error) {
    console.error('保存分账模板失败:', error);
    Message.error('保存失败');
  }
};

// 删除记录
const handleDelete = async (record: any) => {
  try {
    await deleteProfitSharingTemplate(record.id);
    Message.success('删除成功');
    fetchData();
  } catch (error) {
    console.error('删除分账模板失败:', error);
    Message.error('删除失败');
  }
};

// 修改状态
const handleStatusChange = async (record: any, value: boolean) => {
  try {
    await updateProfitSharingTemplate(record.id, {
      ...record,
      status: value ? 1 : 0,
    });
    Message.success('更新成功');
    fetchData();
  } catch (error) {
    console.error('更新状态失败:', error);
    Message.error('更新失败');
  }
};

// 关联对话框相关
const relationDialogVisible = ref(false);
const relationFormRef = ref();
const relationLoading = ref(false);
const currentTemplateId = ref<number>();
const relationData = ref<ProfitSharingTemplateRelation[]>([]);
const partnerOptions = ref<{ id: number; name: string }[]>([]);
const chargingGroupOptions = ref<{ id: number; name: string }[]>([]);

const relationFormData = reactive<ProfitSharingTemplateRelation>({
  templateId: 0,
  chargingGroupId: undefined,
  partnerId: undefined,
  status: 1
});

const relationRules = {
  chargingGroupId: [
    { required: true, message: '请选择站点' }
  ],
  partnerId: [
    { required: true, message: '请选择合伙人' }
  ]
};

// 监听合伙人选择变化
const handlePartnerChange = async (partnerId: number | undefined) => {
  relationFormData.chargingGroupId = undefined; // 清空站点选择
  if (partnerId) {
    // 根据合伙人ID获取站点列表
    try {
      const { data } = await getAllCarChargingGroups({ partnerId });
      // 添加全部站点选项
      chargingGroupOptions.value = [
        { id: 0, name: '全部站点' },
        ...(data || [])
      ];
    } catch (error) {
      console.error('获取站点列表失败:', error);
      Message.error('获取站点列表失败');
    }
  } else {
    chargingGroupOptions.value = [];
  }
};

// 打开关联对话框
const openRelationDialog = async (record: any) => {
  relationDialogVisible.value = true;
  currentTemplateId.value = record.id;
  relationFormData.templateId = record.id;
  await Promise.all([
    loadRelationList(),
    loadPartnerOptions()
  ]);
};

// 加载关联列表
const loadRelationList = async () => {
  if (!currentTemplateId.value) return;
  relationLoading.value = true;
  try {
    const { data } = await getRelationsByTemplateId(currentTemplateId.value);
    relationData.value = data;
  } catch (error) {
    console.error('获取关联列表失败:', error);
    Message.error('获取关联列表失败');
  } finally {
    relationLoading.value = false;
  }
};

// 加载合伙人选项
const loadPartnerOptions = async () => {
  try {
    const { data } = await getAllPartners();
    partnerOptions.value = (data || []).map((item: any) => ({
      id: item.id,
      name: item.realName
    }));
  } catch (error) {
    console.error('获取合伙人列表失败:', error);
    Message.error('获取合伙人列表失败');
  }
};

// 新增关联表单显示状态
const showRelationForm = ref(false);

// 处理新增关联
const handleAddRelation = () => {
  showRelationForm.value = true;
  // 重置表单数据
  Object.assign(relationFormData, {
    id: undefined,
    templateId: currentTemplateId.value || 0,
    partnerId: undefined,
    chargingGroupId: undefined,
    status: 1
  });
};

// 取消关联表单
const cancelRelationForm = () => {
  showRelationForm.value = false;
  relationFormRef.value?.resetFields();
};

// 提交关联表单
const submitRelationForm = async () => {
  try {
    // 检查必填字段
    if (!relationFormData.partnerId) {
      Message.error('请选择合伙人');
      return;
    }
    if (!relationFormData.chargingGroupId && relationFormData.chargingGroupId !== 0) {
      Message.error('请选择站点');
      return;
    }

    if (relationFormData.id) {
      // 编辑模式
      await updateRelation(relationFormData.id, {
        id: relationFormData.id,
        templateId: currentTemplateId.value || 0,
        partnerId: relationFormData.partnerId,
        chargingGroupId: relationFormData.chargingGroupId,
        status: relationFormData.status
      });
      Message.success('更新关联成功');
    } else {
      // 新增模式
      await createRelation({
        templateId: currentTemplateId.value || 0,
        partnerId: relationFormData.partnerId,
        chargingGroupId: relationFormData.chargingGroupId,
        status: relationFormData.status
      });
      Message.success('创建关联成功');
    }
    
    await loadRelationList();
    showRelationForm.value = false;
    relationFormRef.value?.resetFields();
  } catch (error) {
    console.error('保存关联失败:', error);
    Message.error('保存失败');
  }
};

// 编辑关联
const handleRelationEdit = async (record: ProfitSharingTemplateRelation) => {
  showRelationForm.value = true;
  
  // 先加载站点列表，再设置表单数据
  if (record.partnerId) {
    try {
      const { data } = await getAllCarChargingGroups({ partnerId: record.partnerId });
      chargingGroupOptions.value = [
        { id: 0, name: '全部站点' },
        ...(data || [])
      ];
    } catch (error) {
      console.error('获取站点列表失败:', error);
      Message.error('获取站点列表失败');
    }
  }

  // 设置表单数据
  Object.assign(relationFormData, record);
};

// 删除关联
const handleRelationDelete = async (record: ProfitSharingTemplateRelation) => {
  if (!record.id) return;
  try {
    await deleteRelation(record.id);
    Message.success('删除关联成功');
    await loadRelationList();
    // 如果当前正在编辑的是被删除的记录，则重置表单
    if (relationFormData.id === record.id) {
      showRelationForm.value = false;
      relationFormRef.value?.resetFields();
      Object.assign(relationFormData, {
        id: undefined,
        templateId: currentTemplateId.value || 0,
        partnerId: undefined,
        chargingGroupId: undefined,
        status: 1
      });
    }
  } catch (error) {
    console.error('删除关联失败:', error);
    Message.error('删除关联失败');
  }
};

// 关闭关联对话框
const closeRelationDialog = () => {
  relationDialogVisible.value = false;
  showRelationForm.value = false;
  relationFormRef.value?.resetFields();
  currentTemplateId.value = undefined;
  relationData.value = [];
};

// 监听接收方类型变化
const handleReceiverTypeChange = (index: number) => {
  const item = formData.items[index];
  item.receiverAccount = '';
  item.receiverName = '';
};

// 根据手机号查询用户
const handleMobileSearch = async (index: number, mobile: string) => {
  if (!mobile) {
    Message.warning('请输入手机号');
    return;
  }
  
  try {
    const { data } = await getUserByMobile({ mobile });
    if (data?.xcxOpenId) {
      formData.items[index].receiverAccount = data.xcxOpenId;
      Message.success('已自动填充接收方账号');
    } else {
      Message.warning('未找到对应的用户信息');
    }
  } catch (error) {
    console.error('查询用户失败:', error);
    Message.error('查询用户失败');
  }
};

// 初始化
fetchData();
</script>

<style scoped>
.container {
  padding: 0 20px 20px;
}

.general-card {
  margin-top: 16px;
}

.search-area {
  padding: 12px 0;
}

.item-form {
  padding: 16px;
  border: 1px dashed var(--color-border);
  border-radius: 2px;
  margin-bottom: 16px;
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-item {
  margin-top: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.relation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.relation-header .title {
  font-size: 16px;
  font-weight: 500;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}
</style> 